<?php
/*
	2017-02-27
	bach
	v1.00
*/
namespace app\common\model;
class File{
	private $config;
	private $userId;
	private $user;
	function __construct(){
		$this->user = new User;
		$this->config = getConfig('file');
		$this->userId = $this->user->getUserId();
	}
    private function getRandChar($length) {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;
        for ($i = 0; $i < $length; $i++) {
            $str.=$strPol[rand(0, $max)]; //rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }
	private function getSaveName($config){
		$saveName = isset($config['saveName'])?$config['saveName']:"var,8";
		$name = explode(",",$saveName);
		switch($name[0]){
			case "char":
			$saveName = $this->getRandChar($name[1]);
			break;
			case "int":
			$saveName = $this->getRandInt($name[1]);
			break;
			default:
			$saveName = $this->getRandChar(10);
		}
		return $saveName;
	}
	private function getMiniSaveName($path){
		$pos = strrpos($path,'.');
		$path_1 = substr($path,0,$pos);
		$path_2 = substr($path,$pos);
		if(strlen($path_2)>6){
			return $path."_m";
		}
		return $path_1."_m".$path_2;
	}
	function upload($demand){
        if(!$this->userId){
			return array('errormsg'=>'请登录');
		}
        $config = $this->config;
		//查看配置
		if(!$config){
			return array('errormsg'=>'config error','from'=>'file');
		}
		//获取配置
		if(!isset($config[$demand])){
			return array('errormsg'=>'demand error','from'=>'file');
		}
		$config = $config[$demand];
		//检查权限
		if(isset($config['admin'])){
			$admin_check = $config['admin'];
			$admin = new Admin;
			$isAdmin = $admin->is($admin_check);
			if(!isset($isAdmin['state']) || !$isAdmin['state']){
				return $isAdmin;
			}
		}
		$saveName = $this->getSaveName($config);
		$path = $demand;
		$exts = isset($config['exts'])?$config['exts']:"jpg,png,jpeg,gif";
		$size = isset($config['size'])?$config['size']:"1000";
		$ext = isset($config['ext'])?$config['ext']:false;
		$removeExt = 0;
		if($ext == 'none'){
			$removeExt = 1;
		}else if($ext){
			$saveName .= ".$ext";
		}
		if(isset($config['subName'])){
			$subName = $config['subName'];
			$match = preg_match_all("/\{[$][0-9|a-z|_]+\}/",$s = $subName,$result);
			$result = $result[0];
			if(is_array($result)){
				foreach ($result as $value) {
					$key = substr($value,2);
					$key = substr($key,0,strlen($key)-1);
					$k = input("get.$key");
					if(!$k) return array('state'=>0,'errormsg'=>"subName need $key");
					$subName = str_replace($value, $k, $subName);
				}
			}else{
				$key = substr($result,2);
				$key = substr($key,0,strlen($key)-1);
				$k = input("get.$key");
				if(!$k) return array('state'=>0,'errormsg'=>"subName need $key");
				$subName = str_replace($value, $key, $subName);
			}
			$path .= "/".$subName;
		}
	    $file = request()->file(0);
	    // $file = request()
	    // return $file;

	    if(!is_object($file)) $file = request()->file('upfile');
	    if(!is_object($file)) return ['state'=>0,'errormsg'=>'file empty'];
	    $res = $file->validate(['size'=>$size,'ext'=>$exts])->move('link' . DS . $path ,$saveName,$removeExt);
	    if(!is_object($res) && !$res){
	    	return ['state'=>0,'errormsg'=>$file->getError()];
	    }
	    $insert = array(
	    	'user_id' => $this->userId,
	    	'file_code' => $saveName,
	    	'create_time' => time(),
	    	'class' => $config['id']
	    	);
	    $file_id = db('file')->insertGetId($insert);
	    $path = "link/".$path."/".$res->getSaveName();
	    //设置最大宽度
	    if(isset($config['maxWidth'])){

	    	$maxWidth = $config['maxWidth'];
			
			$image = \think\Image::open($path);
			$image_width = $image->width();
			$image_height = $image->height();
			
			if($image_width > $maxWidth){
				$w = $maxWidth;
				$h = $maxWidth*$image_height/$image_width;
				$image->thumb($w,$h)->save($path);
			}

	    }elseif(isset($config['width'])){

	    	$width = $config['width'];

			$image = \think\Image::open($path);
			$image_width = $image->width();
			$image_height = $image->height();
	    	
	    	if(isset($config['height'])){
	    		$height = $config['height'];
	    		if($width == $image_width && $height == $image_height){
	    		}else{
					$w = (float)$width;
					$h = (float)$height;
					$w0 = (float)$image_width;
					$h0 = (float)$image_height;
					//新尺寸比例更宽
					if($w/$h > $w0/$h0){
						$image->thumb($w,$h1=$h*$w0/$w)->save($path);
					//新尺寸比例更长
					}elseif($w/$h < $w0/$h0){
						$image->thumb($w1=$w*$h0/$h,$h)->save($path);
					}
					$image->thumb($w,$h,\think\Image::THUMB_CENTER)->save($path);
				}
			}else{
	    		if($width == $image_width){
	    		}else{
					$w = $width;
					$h = $width*$image_height/$image_width;
					$image->thumb($w,$h)->save($path);
				}
	    	}

	    }
		//附加缩略图处理
		//在配置maxwidth的情况下 单独限制最大宽度 长度随着图片比例进行缩放
		if(isset($config['miniMaxWidth'])){
			$miniMaxWidth = $config['miniMaxWidth'];

			$image = \think\Image::open($path);
			$image_width = $image->width();
			$image_height = $image->height();

			$w = $miniMaxWidth;
			$h = $miniMaxWidth*$image_height/$image_width;
			$path_mini = $this->getMiniSaveName($path);
			$image->thumb($w,$h)->save($path_mini);
		//配置width的情况下 强行设置宽度，长度自动适应 或同样进行强行设置
		//如强行设置长度，则截取图片中间部分
		}elseif(isset($config['miniWidth'])){
			$width = $config['miniWidth'];
			$path_mini = $this->getMiniSaveName($path);

			$image = \think\Image::open($path);
			$image_width = $image->width();
			$image_height = $image->height();

			if(isset($config['miniHeight'])){
				$height = $config['miniHeight'];
				//如设置了长度 则使用截取方式获取图片中间部分
				$w = (float)$width;
				$h = (float)$height;
				$w0 = (float)$image_width;
				$h0 = (float)$image_height;
				//新尺寸比例更宽
				if($w/$h > $w0/$h0){
					$image->thumb($w,$h1=$h*$w0/$w)->save($path_mini);
				//新尺寸比例更长
				}elseif($w/$h < $w0/$h0){
					$image->thumb($w1=$w*$h0/$h,$h)->save($path_mini);
				}
				$image->thumb($w,$h,\think\Image::THUMB_CENTER)->save($path_mini);
			}else{
				//未设置长度
				$w = $width;
				$h = $width*$image_height/$image_width;
				$image->thumb($w,$h)->save($path_mini);
			}
		}
		if(isset($config['secret']) && $config['secret'] ){
			return ['state'=>1,'data'=>['file_id'=>$file_id]];
		}
	    return ['state'=>1,'data'=>['url'=>request()->domain()."/$path"]];

	}
}
